package org.ww.authserver.controller;

import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.ww.authserver.feign.MemberFeiginClient;
import org.ww.authserver.feign.SmsFeiginClient;
import org.ww.authserver.vo.UserLoginVo;
import org.ww.authserver.vo.UserRegistVo;
import org.ww.common.constant.AuthConstant;
import org.ww.common.constant.SmsConstant;
import org.ww.common.exception.GmallExceptionEnum;
import org.ww.common.utils.R;
import org.ww.common.utils.redis.RedisCache;
import org.ww.common.vo.MemberRespVo;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @program: gmall
 * @description: 登录
 * @author: ww
 * @create: 2024-05-08 10:30
 **/

@Slf4j
@Controller
public class LoginController {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SmsFeiginClient smsFeiginClient;
    @Autowired
    private MemberFeiginClient memberFeiginClient;


    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone){
        String key = SmsConstant.SMS_CODE + ":" +phone;
        //1、接口防刷

        //2、60s内当前手机号不能再次发送验证码
        String setTime = redisCache.getCacheObject(key);
        if(StringUtils.isNotBlank(setTime)){
            long time = System.currentTimeMillis() - Long.parseLong(setTime.split("_")[1]);
            if(time < 60000){
                return R.error(GmallExceptionEnum.CODE_SEND_EXCEPTION.getCode(), GmallExceptionEnum.CODE_SEND_EXCEPTION.getMsg());
            }
        }

        //生成随机码
        String randomNum = RandomStringUtils.randomNumeric(6);
        smsFeiginClient.SendCode(phone,randomNum);
        redisCache.setCacheObject(key,randomNum+"_"+System.currentTimeMillis(),5L, TimeUnit.MINUTES);

        return R.ok();
    }


    @PostMapping("/register")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes attributes){
        if(result.hasErrors()){
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        // 校验验证码是否正确
        String key = SmsConstant.SMS_CODE + ":" + vo.getPhone();
        String code = redisCache.getCacheObject(key);
        if(StringUtils.isBlank(code) || !code.split("_")[0].equals(vo.getCode())){
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误!");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        // 真正注册，调用远程服务
        R r = memberFeiginClient.register(vo);
        //TODO:删除redis验证码

        if(r.getCode() == 0){
            //成功
            return "redirect:http://auth.gulimall.com/login.html";
        }else{
            //失败
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo loginVo, RedirectAttributes attributes, HttpSession session){
        //调用远程服务，实现登录功能
        R r = memberFeiginClient.login(loginVo);
        if(r.getCode().equals(0)){
            MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthConstant.LONGINUSER,data);
            return "redirect:http://gulimall.com";
        }else{
            //失败
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthConstant.LONGINUSER);
        if(attribute != null){
            return "redirect:http://gulimall.com";
        }else{
            return "login";
        }
    }

}
